package vn.aptech.leaveManagementSystem.view.personnel;
import java.awt.EventQueue;
import java.awt.ScrollPane;

import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JPopupMenu;
import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.JButton;
import javax.swing.ListSelectionModel;
import javax.swing.LookAndFeel;
import javax.swing.SwingConstants;
import javax.swing.JLabel;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.border.BevelBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.border.LineBorder;
import java.awt.Color;
import javax.swing.JLayeredPane;
import javax.swing.JTextArea;
import javax.swing.JComboBox;
import javax.swing.border.TitledBorder;


import java.awt.Font;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.Timer;
import java.util.Vector;

import javax.swing.border.MatteBorder;
import javax.swing.border.SoftBevelBorder;
import javax.swing.UIManager;

import sun.net.dns.ResolverConfiguration.Options;
import vn.aptech.leaveManagementSystem.business.ViewReport;
import vn.aptech.leaveManagementSystem.business.dto.Application;
import vn.aptech.leaveManagementSystem.business.dto.Holiday;
import vn.aptech.leaveManagementSystem.business.dto.UserLoginInfo;
import vn.aptech.leaveManagementSystem.business.model.MyModel;
import vn.aptech.leaveManagementSystem.business.parse.MyParse;
import vn.aptech.leaveManagementSystem.view.general.General;
import vn.aptech.leaveManagementSystem.view.general.ViewHistoryLeaveForm;
import vn.aptech.leaveManagementSystem.view.util.ComboboxItem;
import vn.aptech.leaveManagementSystem.view.util.TimerTaskForDirector;
import vn.aptech.leaveManagementSystem.view.util.TimerTaskForManager;
import vn.aptech.leaveManagementSystem.view.util.TimerTaskForPersonnel;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JRadioButton;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;

import com.toedter.calendar.JDateChooser;
import com.toedter.calendar.JYearChooser;


public class DemoPersonnelMainForm extends JFrame{
	private JTextField txtfLeavingID;
	private JTextField txtfLeavingStartDate;
	private JTextField txtfLeavingEndDate;
	private JTextField txtfLeavingContact;
	private DefaultTableModel modelEmp;
	private JTextField txtfLeavingBalance;
	private JTable tbLeavingHoliday;
	private DefaultTableModel modelApproval;
	private DefaultTableModel modelLeavingHoliday;
	private MyModel mymodel;
	private Timer timer;
	private JTextArea txtaLeavingReason;
	private JTextField txtfLeavingStatus;
	private JButton btnLeavingNewApp;
	private JButton btnLeavingWithdrawCurrentApp;
	private JButton btnLeavingCancelCurrentApp;
	private JButton btnLeavingViewHistory;
	private int lastedAppStatus;
	private JButton btnLeavingRefresh;
	private JMenuItem miChangePassword;
	private JMenuItem miLogOut;
	private JMenuItem miExit;
	
	public DemoPersonnelMainForm()
	{
		mymodel=new MyModel();
		InitGUI();
		InitAction();
		InitData();
	}

	private void InitData() {
		UpdateSource();
	}

	private void InitAction() {
		CreateTimer();
		
		btnLeavingNewApp.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				ShowSubFormCreateApp();
			}
		});
		
		btnLeavingWithdrawCurrentApp.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				try {
					ResultSet rs=mymodel.applications.getLastedApplication(UserLoginInfo.getUserInfo().getIDEmp());
					if (rs.next())
					{
						Application tempApp=MyParse.toApplication(rs);
						if (tempApp.getStatus()>0)
						{
							btnLeavingWithdrawCurrentApp.setEnabled(false);
							JOptionPane.showMessageDialog(null, "Current application had been approved!");
							UpdateSource();
							return;
						}
					}
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				//------------------------------------------------------
				int choosen=JOptionPane.showOptionDialog(null, "Do you want to withdraw this current application?", "Warning!",JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);
				if (choosen==JOptionPane.OK_OPTION)
				{
					try {
						mymodel.applications.updateApplicationStatus(new Integer(txtfLeavingID.getText()), 3);
						JOptionPane.showMessageDialog(null, "Withdrawal application successful!");
						UpdateSource();
					} catch (NumberFormatException e) {
						e.printStackTrace();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			}
		});
		
		btnLeavingCancelCurrentApp.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				int choosen=JOptionPane.showOptionDialog(null, "Do you want to send a request to Cancel Leaving?", "Warning!",JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);
				if (choosen==JOptionPane.OK_OPTION)
				{
					try {
						mymodel.applications.updateApplicationStatus(new Integer(txtfLeavingID.getText()), 4);
						JOptionPane.showMessageDialog(null, "Cancelation request has been sent!");
						UpdateSource();
					} catch (NumberFormatException e) {
						e.printStackTrace();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			}
		});
		btnLeavingViewHistory.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				ViewHistoryLeaveForm hisForm=new ViewHistoryLeaveForm(UserLoginInfo.getUserInfo().getIDEmp());
				hisForm.setVisible(true);
				hisForm.setAlwaysOnTop(true);
			}
		});
		miChangePassword.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				General gen=new General();
				gen.changPassword(UserLoginInfo.getUserInfo().getIDEmp());
			}
		});
		miLogOut.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				General gen=new General();
				gen.logout();
				close();
			}
		});
		
		miExit.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				General gen=new General();
				gen.exit();
			}
		});
	}
	
	public void close()
	{
		dispose();
	}
	
	private void InitGUI() {
		setTitle("Personnel Main Form");
		setBounds(100, 100, 913, 565);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setLocationRelativeTo(null);
		getContentPane().setLayout(null);
		JMenuBar menuBar = new JMenuBar();
		menuBar.setBorderPainted(false);
		menuBar.setBounds(0, 0, 634, 21);
		getContentPane().add(menuBar);
		JMenu mnGeneral = new JMenu("General");
		menuBar.add(mnGeneral);
		
		miChangePassword = new JMenuItem("Change Password");
		miChangePassword.setIcon(new ImageIcon("icons/gif/16x16/Modify.gif"));
		mnGeneral.add(miChangePassword);
		
		miLogOut = new JMenuItem("Logout");
		miLogOut.setIcon(new ImageIcon("icons/png/16x16/Logout.png"));
		mnGeneral.add(miLogOut);
		
		miExit = new JMenuItem("Exit");
		miExit.setIcon(new ImageIcon("icons/gif/16x16/Exit.gif"));
		mnGeneral.add(miExit);
		
		JMenu mnHelp = new JMenu("Help");
		menuBar.add(mnHelp);
		
		JTabbedPane tpMain = new JTabbedPane(JTabbedPane.TOP);
		tpMain.setBorder(new SoftBevelBorder(BevelBorder.RAISED, null, null, null, null));
		tpMain.setBounds(81, 22, 813, 514);
		getContentPane().add(tpMain);
		modelEmp=new DefaultTableModel(
				new Object[][]{},
				new String[] {
						"ID","FirstName", "LastName", "Gender", "Department","Position","Birthday", "Address", "Email", "Phone", "Join Date", "UserName", "Status"
				});
		modelApproval=new DefaultTableModel(){
			@Override
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};
		modelApproval.addColumn("ID App.");
		modelApproval.addColumn("First Name");
		modelApproval.addColumn("Last Name");
		modelApproval.addColumn("Department");
		modelApproval.addColumn("Position");
		modelApproval.addColumn("Status");
		//----------------------------------------------------------------
		
		JLayeredPane lpLeaving = new JLayeredPane();
		tpMain.addTab("Leaving", null, lpLeaving, null);
		
		JPanel pnlLeaving = new JPanel();
		pnlLeaving.setBounds(10, 0, 792, 475);
		lpLeaving.add(pnlLeaving);
		pnlLeaving.setLayout(null);
		
		JToolBar toolBar = new JToolBar();
		toolBar.setBounds(10, 11, 798, 28);
		pnlLeaving.add(toolBar);
		
		btnLeavingNewApp = new JButton("Create New Leaving App.");
		btnLeavingNewApp.setIcon(new ImageIcon("icons/gif/16x16/Add.gif"));
		toolBar.add(btnLeavingNewApp);
		
		btnLeavingWithdrawCurrentApp = new JButton("Withdraw Current Leaving App.");
		btnLeavingWithdrawCurrentApp.setIcon(new ImageIcon("icons/gif/16x16/Trackback.gif"));
		toolBar.add(btnLeavingWithdrawCurrentApp);
		
		btnLeavingCancelCurrentApp = new JButton("Cancel Current Leaving");
		btnLeavingCancelCurrentApp.setIcon(new ImageIcon("icons/gif/16x16/Cancel.gif"));
		toolBar.add(btnLeavingCancelCurrentApp);
		
		btnLeavingViewHistory = new JButton("View History");
		btnLeavingViewHistory.setIcon(new ImageIcon("icons/gif/16x16/History.gif"));
		toolBar.add(btnLeavingViewHistory);
		
		btnLeavingRefresh = new JButton("Refresh");
		btnLeavingRefresh.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				UpdateSource();
			}
		});
		btnLeavingRefresh.setIcon(new ImageIcon("icons/gif/16x16/Refresh.gif"));
		toolBar.add(btnLeavingRefresh);
		
		JPanel pnlLeavingCurrentApp = new JPanel();
		pnlLeavingCurrentApp.setBorder(new TitledBorder(null, "Lasted Leave Application", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		pnlLeavingCurrentApp.setBounds(121, 50, 535, 279);
		pnlLeaving.add(pnlLeavingCurrentApp);
		pnlLeavingCurrentApp.setLayout(null);
		
		txtfLeavingContact = new JTextField();
		txtfLeavingContact.setEditable(false);
		txtfLeavingContact.setBounds(102, 209, 416, 20);
		pnlLeavingCurrentApp.add(txtfLeavingContact);
		txtfLeavingContact.setColumns(10);
		
		JLabel lblLeavingContact = new JLabel("Contact:");
		lblLeavingContact.setBounds(21, 212, 46, 14);
		pnlLeavingCurrentApp.add(lblLeavingContact);
		
		JLabel lblLeavingStatus = new JLabel("Status:");
		lblLeavingStatus.setBounds(21, 243, 46, 14);
		pnlLeavingCurrentApp.add(lblLeavingStatus);
		
		JLabel lblLeavingReason = new JLabel("Reason:");
		lblLeavingReason.setBounds(21, 126, 46, 14);
		pnlLeavingCurrentApp.add(lblLeavingReason);
		
		txtaLeavingReason = new JTextArea();
		txtaLeavingReason.setEditable(false);
		txtaLeavingReason.setBounds(102, 121, 416, 79);
		pnlLeavingCurrentApp.add(txtaLeavingReason);
		
		JLabel lblLeavingEndDate = new JLabel("End date:");
		lblLeavingEndDate.setBounds(21, 93, 71, 14);
		pnlLeavingCurrentApp.add(lblLeavingEndDate);
		
		txtfLeavingEndDate = new JTextField();
		txtfLeavingEndDate.setEditable(false);
		txtfLeavingEndDate.setBounds(102, 90, 416, 20);
		pnlLeavingCurrentApp.add(txtfLeavingEndDate);
		txtfLeavingEndDate.setColumns(10);
		
		txtfLeavingStartDate = new JTextField();
		txtfLeavingStartDate.setEditable(false);
		txtfLeavingStartDate.setBounds(102, 60, 416, 20);
		pnlLeavingCurrentApp.add(txtfLeavingStartDate);
		txtfLeavingStartDate.setColumns(10);
		
		txtfLeavingID = new JTextField();
		txtfLeavingID.setEditable(false);
		txtfLeavingID.setBounds(102, 29, 416, 20);
		pnlLeavingCurrentApp.add(txtfLeavingID);
		txtfLeavingID.setColumns(10);
		
		JLabel lblLeavingID = new JLabel("ID:");
		lblLeavingID.setBounds(21, 32, 46, 14);
		pnlLeavingCurrentApp.add(lblLeavingID);
		
		JLabel lblLeavingStartDate = new JLabel("Start date:");
		lblLeavingStartDate.setBounds(21, 63, 71, 14);
		pnlLeavingCurrentApp.add(lblLeavingStartDate);
		
		txtfLeavingStatus = new JTextField();
		txtfLeavingStatus.setEditable(false);
		txtfLeavingStatus.setColumns(10);
		txtfLeavingStatus.setBounds(102, 240, 416, 20);
		pnlLeavingCurrentApp.add(txtfLeavingStatus);
		
		JLabel lblLeavingBalance = new JLabel("Leave Balance:");
		lblLeavingBalance.setFont(new Font("Tahoma", Font.PLAIN, 12));
		lblLeavingBalance.setForeground(Color.BLUE);
		lblLeavingBalance.setBounds(131, 346, 81, 14);
		pnlLeaving.add(lblLeavingBalance);
		
		txtfLeavingBalance = new JTextField();
		txtfLeavingBalance.setEditable(false);
		txtfLeavingBalance.setFont(new Font("Tahoma", Font.BOLD, 12));
		txtfLeavingBalance.setForeground(Color.DARK_GRAY);
		txtfLeavingBalance.setBounds(227, 343, 204, 20);
		pnlLeaving.add(txtfLeavingBalance);
		txtfLeavingBalance.setColumns(10);
		
		//-----------------------------------------------------------
		//Table Holiday
		tbLeavingHoliday = new JTable();
		modelLeavingHoliday=new DefaultTableModel(){
			@Override
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};
		modelLeavingHoliday.addColumn("ID");
		modelLeavingHoliday.addColumn("Event");
		modelLeavingHoliday.addColumn("Start Date");
		modelLeavingHoliday.addColumn("End Date");
		tbLeavingHoliday.setModel(modelLeavingHoliday);
		tbLeavingHoliday.getColumnModel().getColumn(0).setPreferredWidth(70);
		tbLeavingHoliday.getColumnModel().getColumn(1).setPreferredWidth(267);
		tbLeavingHoliday.getColumnModel().getColumn(2).setPreferredWidth(105);
		tbLeavingHoliday.getColumnModel().getColumn(3).setPreferredWidth(110);
		tbLeavingHoliday.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		//tbLeavingHoliday.setBounds(10, 63, 772, 56);
		JScrollPane spLeavingHoliday=new JScrollPane(tbLeavingHoliday);
		spLeavingHoliday.setBounds(10, 401, 772, 63);
		pnlLeaving.add(spLeavingHoliday);
		//-----------------------------------------------------------
		
		JLabel lblLeavingHoliday = new JLabel("Upcoming holiday");
		lblLeavingHoliday.setFont(new Font("Tahoma", Font.PLAIN, 11));
		lblLeavingHoliday.setForeground(Color.BLUE);
		lblLeavingHoliday.setBounds(10, 385, 98, 14);
		pnlLeaving.add(lblLeavingHoliday);
		
		JLabel jlblBackground = new JLabel("");
		jlblBackground.setBounds(0, 23, 82, 512);
		getContentPane().add(jlblBackground);
		jlblBackground.setBorder(new LineBorder(new Color(0, 0, 0)));
		jlblBackground.setIcon(new ImageIcon("backgrounds/Background0.png"));
		
		JLabel lblWellcome = new JLabel("New label");
		lblWellcome.setBorder(new BevelBorder(BevelBorder.RAISED, null, null, null, null));
		lblWellcome.setHorizontalAlignment(SwingConstants.RIGHT);
		lblWellcome.setFont(new Font("Tahoma", Font.BOLD, 11));
		lblWellcome.setForeground(UIManager.getColor("ComboBox.selectionBackground"));
		lblWellcome.setBounds(637, 0, 257, 21);
		
		getContentPane().add(lblWellcome);
		String strWellcome="User: ";
		if (UserLoginInfo.getUserInfo().isGender())
			strWellcome=strWellcome+"Mr. ";
		else
			strWellcome=strWellcome+"Mrs. ";
		strWellcome=strWellcome+UserLoginInfo.getUserInfo().getFirstName()+" "+UserLoginInfo.getUserInfo().getLastName();
		lblWellcome.setText(strWellcome);
	}
	
	private static void addPopup(Component component, final JPopupMenu popup) {
		component.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				if (e.isPopupTrigger()) {
					showMenu(e);
				}
			}
			public void mouseReleased(MouseEvent e) {
				if (e.isPopupTrigger()) {
					showMenu(e);
				}
			}
			private void showMenu(MouseEvent e) {
				popup.show(e.getComponent(), e.getX(), e.getY());
			}
		});
	}
	
	public void RemoveAllRows(DefaultTableModel tablemodel)
	{
		int n=tablemodel.getRowCount();
		for (int i = n-1; i >=0; i--) {
			tablemodel.removeRow(i);
		}
	}
	
	public void UpdateLastedApplication()
	{
		try {
			ResultSet rs = mymodel.applications.getLastedApplication(UserLoginInfo.getUserInfo().getIDEmp());
			if(rs.next())
			{
				Application tempApp=MyParse.toApplication(rs);
				txtfLeavingID.setText(new Integer(tempApp.getIDApplication()).toString());
				txtfLeavingStartDate.setText(tempApp.getStartDate().toString());
				txtfLeavingEndDate.setText(tempApp.getEndDate().toString());
				txtfLeavingContact.setText(tempApp.getContact());
				txtaLeavingReason.setText(tempApp.getReason());
				int status=tempApp.getStatus();
				lastedAppStatus=status;
				if (status==0)
					txtfLeavingStatus.setText("Awaiting approval to Leave");
				if (status==1)
					txtfLeavingStatus.setText("Approved this leave application");
				if (status==2)
					txtfLeavingStatus.setText("Rejected this leave application");
				if (status==3)
					txtfLeavingStatus.setText("Withdrawed this application");
				if (status==4)
					txtfLeavingStatus.setText("Awaiting approval to Cancel Leaving");
				if (status==5)
					txtfLeavingStatus.setText("Approved to Cancel Leaving");
				if (status==6)
					txtfLeavingStatus.setText("Rejected to Cancel Leaving");
				
				if (status==0 || status==4)
					btnLeavingNewApp.setEnabled(false);
				else
					btnLeavingNewApp.setEnabled(true);
				
				if (status>0)
					btnLeavingWithdrawCurrentApp.setEnabled(false);
				else
					btnLeavingWithdrawCurrentApp.setEnabled(true);
				
				if (status==1)
					btnLeavingCancelCurrentApp.setEnabled(true);
				else
					btnLeavingCancelCurrentApp.setEnabled(false);
			}	
			else
			{
				txtfLeavingID.setText("");
				txtfLeavingStartDate.setText("");
				txtfLeavingEndDate.setText("");
				txtfLeavingContact.setText("");
				txtaLeavingReason.setText("");
				txtfLeavingStatus.setText("");
				btnLeavingWithdrawCurrentApp.setEnabled(false);
				btnLeavingCancelCurrentApp.setEnabled(false);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void UpdateLeaveBalance()
	{
		try {
			int lb=mymodel.employees.getLeaveBalanceInThisTime(UserLoginInfo.getUserInfo().getIDEmp());
			txtfLeavingBalance.setText(new Integer(lb).toString());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void UpdateDataTableHoliday()
	{
		try {
			ResultSet rs=mymodel.holidays.getUpcomingHolidays();
			RemoveAllRows(modelLeavingHoliday);
			while (rs.next())
			{
				Holiday tempHol=MyParse.toHoliday(rs);
				Vector<Object> v=new Vector<Object>();
				v.add(tempHol.getIDHoliday());
				v.add(tempHol.getEvent());
				v.add(tempHol.getStartDate().toString());
				v.add(tempHol.getEndDate().toString());
				modelLeavingHoliday.insertRow(modelLeavingHoliday.getRowCount(),v);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void UpdateSource()
	{
		UpdateLastedApplication();
		UpdateLeaveBalance();
		UpdateDataTableHoliday();
	}
	
	public void ShowSubFormCreateApp()
	{
		DemoCreateNewApplicationForPersonnel createAppForm=new DemoCreateNewApplicationForPersonnel(this, UserLoginInfo.getUserInfo().getIDEmp());
		createAppForm.setVisible(true);
		createAppForm.setAlwaysOnTop(true);
		this.setEnabled(false);
	}
	

	
	public void CreateTimer()
	{	
		timer=new Timer();
		timer.schedule(new TimerTaskForPersonnel(this),1000,24000);
	}
}
